package com.yycx.module.bus.provider.handler.client;

import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.utils.ApiAssert;
import com.yycx.groovy.provider.script.MyGroovyScriptEngine;
import com.yycx.module.bus.client.entity.hy.HyOrderDetail;
import com.yycx.module.system.client.entity.SysFormula;
import com.yycx.module.system.provider.service.SysFormulaService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 订单辅助类
 *
 * @author zyf
 */
@Component
@AllArgsConstructor
public class OrderHelp {

    private final SysFormulaService sysFormulaService;
    private final MyGroovyScriptEngine groovyScriptEngine;

    /**
     * 计算市场结算金额
     *
     * @param orderDetailsVo
     * @return
     */
    public BigDecimal calculateSettleAmount(HyOrderDetailsVo orderDetailsVo) {
        HyOrderDetail orderDetails = orderDetailsVo.getHyOrderDetail();
        BigDecimal settleAmount = new BigDecimal("0");

        String settleFormulaContent = orderDetails.getSettleFormulaContent();
        if (FlymeUtils.isNotEmpty(settleFormulaContent)) {
            ApiAssert.isNotEmpty("结算公式未配置", settleFormulaContent);
            try {
                Map<String, Object> variable = orderDetailsVo.getVariable();
                settleAmount = groovyScriptEngine.executeBigDecimal(settleFormulaContent, variable);
            } catch (Exception e) {
                e.printStackTrace();
                ApiAssert.failure("结算金额计算异常");
            }
        }
        return settleAmount;
    }

    /**
     * 计算利润
     *
     * @param orderDetailsVo
     * @return
     */
    public BigDecimal calculateProfitAmount(HyOrderDetailsVo orderDetailsVo) {
        HyOrderDetail orderDetails = orderDetailsVo.getHyOrderDetail();
        BigDecimal profitAmount = new BigDecimal("0");
        String profitAmountFormulaContent = orderDetails.getProfitAmountFormulaContent();
        if (FlymeUtils.isNotEmpty(profitAmountFormulaContent) || FlymeUtils.isNotEmpty(profitAmountFormulaContent)) {
            if (FlymeUtils.isEmpty(profitAmountFormulaContent)) {
                ApiAssert.isNotEmpty("利润公式不存在", profitAmountFormulaContent);
            }
            try {
                Map<String, Object> variable = orderDetailsVo.getVariable();
                profitAmount = groovyScriptEngine.executeBigDecimal(profitAmountFormulaContent, variable);
            } catch (Exception e) {
                e.printStackTrace();
                ApiAssert.failure("结算金额计算异常");
            }

        } else {
            orderDetails.setProfitAmount(profitAmount);
        }
        return profitAmount;
    }
}
